/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////Author: Shahab.Alishahian@gmail.com SA	
///////////////Target:The following methods are here to handle all GAPI functions.
///////////////Version:1.1
///////////////CopyRight: 2014 Noranj Co.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//*************************************************************************************************************
// USER ADMIN  
// NEW APPROVED
function setAddUser(data,friends){
	if(data!='undefined'){
		var request = gapi.client.jb.user.fb.get({
			'id':data.facebookId
		});
		 request.execute(function(jsonResp, rawResp) {
			if(jsonResp.code==-32099){
				request = gapi.client.jb.user.insert({
		  			 'address': data.address,
		  			 'age':data.age,
		  			 'city':data.city,
		  			 'country':data.country,
		  			 'dateCreated':data.dateCreated,
		  			 'email':data.email,
		  			 'facebookId':data.facebookId,
		  			 'firstName':data.firstName,
		  			 'role':'USER',
		  			 'gender':data.gender,
		  			 'ipAddress':data.ipAddress,
		  			 'lastName':data.lastName,
		  			 'merchantId':data.merchantId 
		  		 });
		  		 request.execute(function(jsonResp, rawResp) {
		  			$("#jsUserId").val(jsonResp.id);
		  	  	  	//REM:SA:20131102:The line in below is for add the list of boards .
		  	  	  	getBoardListById($("#jsUserId").val());
		  	    });
	  	  	}
			else{
				$("#jsUserId").val(jsonResp.id);
				getMerchantInfo(jsonResp.merchantId);
				//REM:SA:20131102:The line in below is for adding the list of boards .
				if(jsonResp.role === 'ADMIN'){ //TODO:SA: Remember to fix this part it still doesn't return role in this object.
					loadparts(4);
					bringNext(3);
					getBoardListAdmin($("#jsUserId").val());
				}
				else{
					loadparts(3);
					bringNext();
					getBoardListById($("#jsUserId").val());
				}
			}
	    });
	}
	
}

//***************************************************************************************************
//
function getBoardListAdmin(userId){
	
	if(userId!='undefined'){
		var request = gapi.client.jb.board.user.listAny({
			'anyuserid':userId
		});
		 request.execute(function(jsonResp, rawResp) {
			 if(jsonResp.items != undefined){
				 
			 }
			 $("#boardListAdmin").append(createBoardsAdmin(jsonResp));
			 	showUserCreator();

		 });
	}
}
//fetch all boards which logged in 
function getBoardListById(anyuserid){
	
	if(anyuserid!='undefined'){
		var request = gapi.client.jb.board.user.listAny({
			'anyuserid':anyuserid
		});
		 request.execute(function(jsonResp, rawResp) {
			 $("#boardlist").append(createBoards(jsonResp));
		 });
	}
}

//***************************************************************************************************
//Creating admin view panel 
function createBoardsAdmin(data){
	var strReturn ='';
	var boardImageURL = '';
	for (var i = 0; i < data.items.length; i++){
		if(data.items[i].boardItem.imageURL.indexOf("http")!=-1)
			boardImageURL = data.items[i].boardItem.imageURL
		else{
			var jsDefaulURL = document.getElementById("jsDefaulURL");
			boardImageURL= jsDefaulURL.value + data.items[i].boardItem.imageURL;
		}
		var d = new Date(parseInt(data.items[i].timestamp));
		strReturn += '<div id="'+ data.items[i].id + '" class="uiCommentRow" onclick="showBoard(this,\''+ data.items[i].id + '\',\''+ boardImageURL + '\',\'' + data.items[i].boardItem.url + '\')" >' ;
		strReturn += '<table><tr><td>' ;
		strReturn += '<a href="'+ data.items[i].boardItem.url +'" target="_blank"><img src="'+ boardImageURL +'" height="65px" width="65px" /></a>';
		strReturn += '</td><td valign="top" width="100%">';
		strReturn += '<div><span class="textSimple">' + data.items[i].boardItem.title +'</span></div>' ;
		strReturn += '<div class="textDate">' + $.datepicker.formatDate('yy-mm-dd',d) +'</div>';
		strReturn += '<div class="textUser" id="'+ data.items[i].userId +'" ></div>';
		strReturn += '</td><td valign="top"><a href="#" id="removeBoard" class="fancyboxclose" onclick="removeBoard(\''+ data.items[i].id + '\')"></a><td></tr></table>';
		strReturn += '</div>';
	}
	return strReturn;
}

//Creating noraml user view panel
function createBoards(data){
	var strReturn ='';
	var boardImageURL = '';
	for (var i = 0; i < data.items.length; i++){
		if(data.items[i].boardItem.imageURL.indexOf("http")!=-1)
			boardImageURL = data.items[i].boardItem.imageURL
		else{
			var jsDefaulURL = document.getElementById("jsDefaulURL");
			boardImageURL= jsDefaulURL.value + data.items[i].boardItem.imageURL;
		}

		strReturn += '<div id="'+ data.items[i].id + '" class="boardItem" onclick="getBoard(\''+ data.items[i].id + '\',\''+ boardImageURL + '\')" >' ;
		strReturn += '<table><tr><td>' ;
		strReturn += '<a href="'+ data.items[i].boardItem.url +'"><img src="'+ boardImageURL +'" height="65px" width="65px"/></a>';
		strReturn += '</td><td valign="top">';
		strReturn += '<span class="textSimple">' + data.items[i].boardItem.title +'</span>' ; 
		strReturn += '</td></tr></table>';
		strReturn += '</div>';
	}
	return strReturn;
}

//***************************************************************************************************
//Create a row as conversation row and return to others method
function createConversation(data,contributer){
	var d = new Date(parseInt(data.timestamp));
	var strReturn ='';	
	
	if (data.status === "NEW")
		strReturn += '<div id="d'+ data.id + '" class="notApprovedRow" >' ;
	else
		strReturn += '<div id="d'+ data.id + '" class="uiCommentRow" >' ;

	strReturn += '<table valign="top" width="100%" border="0">';
	strReturn += '<tr>';
		strReturn += '<td rowspan="3" valign="top" width="70px">' ;
			strReturn += '<a target="_blank" href="https://www.facebook.com/' + contributer.facebookId + '">';
			strReturn += '<img src= "https://graph.facebook.com/' + contributer.facebookId + '/picture" height="50px" width="50px"/></a>';
		strReturn += '</td>';
		strReturn += '<td valign="top" colspan="5"><div><span class="textConv">' + contributer.firstName + ' ' + contributer.lastName + '</span></div></td>' ;
		strReturn += '<td width="20px"><a href="#" id="removeMessage" class="fancyboxclose" onclick="removeDiscussion(\''+ data.id + '\')"></a></td>' ;
	strReturn += '</tr>';
	strReturn += '<tr>';
		strReturn += '<td colspan="5" class="textSimple"><div id="edit'+ data.id +'">' + data.discussion +'</div></td>';
		strReturn += '<td></td>';
	strReturn += '</tr>';
	strReturn += '<tr>';
		strReturn += '<td  width="65px"><div class="textDate">' + $.datepicker.formatDate('yy-mm-dd',d) +'</div></td>';
		strReturn += '<td>';
		strReturn += '<div style="white-space: nowrap;">';
			strReturn += '<span  class="textConv" >'+ data.status +'</span>';
		strReturn += '</div>';
		strReturn += '</td>';
		strReturn += '<td width="20px"><a href="#" id="confirmMessage" class="fancyboxsend" title="notify" onclick="sendNotification(\''+ data.id + '\',\'' + contributer.facebookId +  '\')"></a></td>';
		strReturn += '<td width="20px"><a href="#" id="replyMessage" class="fancyboxreply" title="reply" onclick="replyDiscussion(\''+ contributer.id +  '\',\''+ contributer.facebookId + '\')"></a></td>';
		strReturn += '<td width="20px"><a href="#" id="editMessage" class="fancyboxedit" title="edit" onclick="editDiscussion(\''+ data.id + '\')"></a></td>';
		strReturn += '<td width="20px"><a href="#" id="confirmMessage" class="fancyboxok" title="approve" onclick="approveDiscussion(\''+ data.id + '\')"></a></td>';
	strReturn += '</tr></div>';
	return strReturn;
	//console.log(strReturn);
}

//***************************************************************************************************
//Listing all rows of a user in admin panel and called in <<loadConversationsAdmin>>.
function getContributerAdmin(data){
	var contributer = {};
	if(data!='undefined'){
		var request = gapi.client.jb.user.get({
			'id':data.userId
		});
		
		request.execute(function(jsonResp, rawResp) {
			contributer["id"] = jsonResp.id;
			contributer["firstName"] = jsonResp.firstName;
			contributer["lastName"] = jsonResp.lastName;
			contributer["facebookId"] = jsonResp.facebookId;
			$("#baordDiscussionList").append(createConversation(data,contributer));
		});
	}
}
//Listing all rows of a user in user view and called in <<loadConversations>>.
function getContributer(data){
	var contributer = {};
	if(data!='undefined'){
		var request = gapi.client.jb.user.get({
			'id':data.userId
		});
		
		request.execute(function(jsonResp, rawResp) {
			contributer["id"] = jsonResp.id;
			contributer["firstName"] = jsonResp.firstName;
			contributer["lastName"] = jsonResp.lastName;
			contributer["facebookId"] = jsonResp.facebookId;
			$("#convlist").append(createConversation(data,contributer));
		});
	}
}
//***************************************************************************************************
function loadConversationsAdmin(boardId){
	console.log('boardId:' + boardId);
	
	if(boardId!='undefined'){
		var request = gapi.client.jb.board.get({
			'id':boardId
		});
		 request.execute(function(jsonResp, rawResp) {
			 $('.imageRef').each(function(){
			        $(this).attr("src", jsonResp.boardItem.imageURL );
			    });
			 
		});
		 
		var request0 = gapi.client.jb.board.listDiscussion({
			'boardId':boardId
		});
		 request0.execute(function(jsonResp, rawResp) {
			 for (var i = 0; i < jsonResp.items.length; i++){
				 getContributerAdmin(jsonResp.items[i]);
			 }
		 });
	}
}

function loadConversations(boardId){
	console.log('boardId:' + boardId);
	
	if(boardId!='undefined'){
		var request0 = gapi.client.jb.board.listDiscussion({
			'boardId':boardId
		});
		 request0.execute(function(jsonResp, rawResp) {
			 for (var i = 0; i < jsonResp.items.length; i++){
				 getContributer(jsonResp.items[i]);
			 }
		 });
	}
}
//***************************************************************************************************
function showBoard(me,boardId,imageUrl,boardUrl){
	$(".uiCommentRow").removeClass("boardItemSelected");
	$(me).addClass("boardItemSelected");
	$("#jsSelectedBoardId").val(boardId);
	$("#jsSelectedBoardURL").val(boardUrl);
	$("#jsSelectedImageURL").val(imageUrl);
	$("#baordDiscussionList").empty();
	loadConversationsAdmin(boardId);
}
function getBoard(boardId,boardImageURL){
	bringNext();
	$("#jsSelectedBoardId").val(boardId);
	loadConversations(boardId);
	
	$('.imageRef').each(function(){
		$(this).attr("src",  boardImageURL);
	});
}

//*************************************************************************************************************
function addBoardItemDiscussion(data,objectHolder,recfacebookId){
	 var request = gapi.client.jb.board.addDiscussion({
	 'boardId':data.boardId,
	 'date':data.date,
	 'discussion':data.discussion,
	 'faceBookReference':data.faceBookReference,
	 'userId':data.userId,
	 'status':data.status,
	 'parentDiscussionId':data.parentDiscussionId
	 });
	 request.execute(function(jsonResp, rawResp) { 
		 //addConversations($("#jsSelectedBoardId").val(),data,objectHolder);
		 	 addConversations(jsonResp.id,data,objectHolder);
		 if(recfacebookId!=undefined){
			 showEditMessagePanel(data.discussion,jsonResp.id,recfacebookId);
		 }
    });
}

//*************************************************************************************************************
//To remove each board we have a small button on board row and by clicking on it this method will be fired to remove a board and sub discussion(s).
function removeBoard(boardId)
{
	var request = gapi.client.jb.board.remove({
		 'id':boardId
		 });
		 request.execute(function(jsonResp, rawResp) { 
			 var object = document.getElementById(boardId); 
			 $(object).effect( "blind", null, 500, null);
	    });
	
}

//*************************************************************************************************************

function removeDiscussion(boardDiscussionId)
{
	var request = gapi.client.jb.board.discussion.remove({
		 'id':boardDiscussionId,
		 'userId': $('#jsUserId').val()
		 });
		 request.execute(function(jsonResp, rawResp) { 
			 var object = document.getElementById("d"+ boardDiscussionId); 
			 $(object).effect( "blind", null, 500, null);
	    });

}
//To approve each discussion we have a small button on disucssion row and by clicking on it this method will be fired.
function approveDiscussion(boardDiscussionId){
	var request = gapi.client.jb.board.discussion.updateStatus({
		 'id':boardDiscussionId,
		 'status':'APPROVED' 
		 });
		 request.execute(function(jsonResp, rawResp) { 
			 var object = document.getElementById("d"+ boardDiscussionId); 
			 $(object).effect( "bounce", null, 500, null);
			 $(object).removeClass("notApprovedRow");
			 $(object).addClass("uiCommentRow");
	    });
}

//To edit each discussion we have a small button on disucssion row and by clicking on it this method will be shown in a textarea to edit.
function editDiscussion(boardDiscussionId){
	var request = gapi.client.jb.board.getDiscussion({
		 'discId':boardDiscussionId
		 });
		 request.execute(function(jsonResp, rawResp) { 
			 showEditMessagePanel(jsonResp.discussion,boardDiscussionId)
	    });
	
}

//To reply to each discussion we have a small button on disucssion row and by clicking on it this method will be shown in a empty textarea to reply smth.
function replyDiscussion(userId,facebookId){
	replyToMessage(userId,facebookId);
}

//To send a notification to facebook to let the customers must check the url which put the comment.
function sendNotification(id,recfacebookId){
	var contactId = recfacebookId;
	var senderId = $("#fbid").val();
	var obj = document.getElementById('edit' + id + '');
	var notifyText = obj.innerHTML;
	var url =  $("#jsSelectedBoardURL").val();
	var imageUrl = $("#jsSelectedImageURL").val();
	sendANotification(contactId,senderId,notifyText,url,imageUrl);
}

//*************************************************************************************************************

function getUserInfo(userId){
	var request = gapi.client.jb.user.get({
		 'id':userId 
		 });
		 request.execute(function(jsonResp, rawResp) { 
			 var object = document.getElementById(userId); 
			 $(object).html(jsonResp.firstName + ' ' + jsonResp.lastName);
	    });
}
//*************************************************************************************************************

function getMerchantInfo(merchantId){
	var request = gapi.client.jb.merchant.get({
		 'id':merchantId
		 });
		 request.execute(function(jsonResp, rawResp) { 
			 var object = document.getElementById("jsDefaulURL"); 
			 object.value = jsonResp.webURL;
	    });

}

function updateDiscussion(discussionId, discussionText){
	
	var request = gapi.client.jb.board.discussion.updateDiscussion({
		 'id':discussionId,
		 'discussion':discussionText,
		 'status': 'APPROVED'
		 });
		 
	request.execute(function(jsonResp, rawResp) { 
			 console.log('Updated to ' + discussionText);
	    });
}